import React from 'react';
import { Dormitory, dormitoryStatusOptions, dormitoryTypeOptions } from '../../shared/models';

interface DormitoryTableProps {
  dormitories: Dormitory[];
  onEdit: (dormitory: Dormitory) => void;
  onDelete: (id: string) => void;
}

const DormitoryTable: React.FC<DormitoryTableProps> = ({
  dormitories,
  onEdit,
  onDelete
}) => {
  // 渲染状态标签
  const renderStatusTag = (status: string) => {
    const statusOption = dormitoryStatusOptions.find(option => option.value === status);
    return statusOption ? (
      <span className={`status-tag ${status}`} style={{ backgroundColor: statusOption.color }}>
        {statusOption.label}
      </span>
    ) : null;
  };

  // 计算入住率
  const getOccupancyRate = (dorm: Dormitory) => {
    if (dorm.capacity === 0) return '0%';
    const rate = (dorm.currentOccupancy / dorm.capacity) * 100;
    return `${Math.round(rate)}%`;
  };

  return (
    <div className="dormitory-table-container">
      <table className="dormitory-table">
        <thead>
          <tr>
            <th>楼栋</th>
            <th>房间号</th>
            <th>类型</th>
            <th>容量</th>
            <th>当前入住</th>
            <th>入住率</th>
            <th>楼层</th>
            <th>管理员</th>
            <th>联系电话</th>
            <th>状态</th>
            <th>创建时间</th>
            <th>操作</th>
          </tr>
        </thead>
        <tbody>
          {dormitories.map((dormitory) => (
            <tr key={dormitory.id}>
              <td>{dormitory.building}</td>
              <td>{dormitory.roomNumber}</td>
              <td>{dormitoryTypeOptions.find(option => option.value === dormitory.type)?.label || dormitory.type}</td>
              <td>{dormitory.capacity}</td>
              <td>{dormitory.currentOccupancy}</td>
              <td>{getOccupancyRate(dormitory)}</td>
              <td>{dormitory.floor}</td>
              <td>{dormitory.supervisor || '-'}</td>
              <td>{dormitory.phoneNumber || '-'}</td>
              <td>{renderStatusTag(dormitory.status)}</td>
              <td>{dormitory.createdAt ? new Date(dormitory.createdAt).toLocaleDateString() : '-'}</td>
              <td>
                <div className="action-buttons">
                  <button className="btn-edit" onClick={() => onEdit(dormitory)}>编辑</button>
                  <button className="btn-delete" onClick={() => onDelete(dormitory.id)}>删除</button>
                </div>
              </td>
            </tr>
          ))}
        </tbody>
      </table>
      {dormitories.length === 0 && (
        <div className="empty-state">
          <p>暂无宿舍数据</p>
        </div>
      )}
    </div>
  );
};

export default DormitoryTable;